package controllers

import (
	"LoginTemplate/models"
	"LoginTemplate/utils"
	"fmt"
	"golang.org/x/crypto/bcrypt"
	"time"
)

type UserController struct {
	BaseController
}

type loginProto struct {
	Account  string `json:"account"`
	Password string `json:"password"`
	Mobile   string `json:"mobile"`
	//Phone    string `json:"phone"`
}

type loginData struct {
	UserInfo models.Staff `json:"user"`
	Token    string       `json:"token"`
}

type passwordProto struct {
	OldPassword string `json:"old_password"`
	NewPassword string `json:"new_password"`
}

type staffProto struct {
	Id           int    `json:"id"`
	Account      string `json:"account"`
	Mobile       string `json:"mobile"`
	Password     string `json:"password"`
	Username     string `json:"username"`
	Status       int    `json:"status"`
	Avatar       string `json:"avatar"`
	UpdatedAt    string `json:"updated_at"`
	CreatedAt    string `json:"created_at"`
	RoleId       int    `json:"role_id"`
	DepartmentId int    `json:"department_id"`
	ShopId       int    `json:"shop_id"`
}

type userListProto struct {
	Page    int    `json:"page"`
	Limit   int    `json:"limit"`
	Keyword string `json:"keyword"`
}

type saveMyInfoProto struct {
	Mobile   string `json:"mobile"`
	Username string `json:"username"`
	Avatar   string `json:"avatar"`
	Password string `json:"password"`
}

func (u *UserController) Login() {
	var request loginProto
	var userInfo models.Staff
	err := u.ShouldBind(&request)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var selectLogin models.Staff
	sql := "select * from staff where mobile = ?"
	models.DB.Debug().Raw(sql, request.Mobile).Scan(&selectLogin)
	if selectLogin.Mobile == "" {
		var client utils.Client1
		sql1 := "select * from client where client_phone = ?"
		models.DB.Debug().Raw(sql1, request.Mobile).Scan(&client)
		token, err := utils.UserToken(client)
		if err == nil {
			u.JsonMsg(200, loginData{
				UserInfo: userInfo,
				Token:    token,
			}, "success")
		} else {
			u.JsonMsg(500, "", "生成访问令牌失败")
		}
	}
	userInfo, err = userInfo.VerifyPassword(request.Account, request.Password)
	if err == nil {
		token, err := utils.MakeToken(userInfo)
		if err == nil {
			u.JsonMsg(200, loginData{
				UserInfo: userInfo,
				Token:    token,
			}, "success")
		} else {
			u.JsonMsg(500, "", "生成访问令牌失败")
		}
	} else {
		u.JsonMsg(500, "", string(err.Error()))
	}
}

func (u *UserController) Password() {
	var request passwordProto
	err := u.ShouldBind(&request)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	if request.OldPassword == "" {
		u.JsonMsg(500, "", "请输入原密码")
	}
	if request.NewPassword == "" {
		u.JsonMsg(500, "", "请输入新密码")
	}
	_, err = GlobalUserInfo.VerifyPassword(GlobalUserInfo.Account, request.OldPassword)
	if err != nil {
		u.JsonMsg(500, "", "原密码输入错误")
	}
	err = GlobalUserInfo.ModifyPassword(GlobalUserInfo.Account, request.NewPassword)
	if err == nil {
		u.JsonMsg(200, "", "保存成功")
	} else {
		u.JsonMsg(500, "", string(err.Error()))
	}
}

func (u *UserController) SaveUser() {
	var request staffProto
	err := u.ShouldBind(&request)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	if request.Account == "" {
		u.JsonMsg(500, "", "请输入账号")
	}
	if request.Password != "" {
		bcryptByte, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
		if err != nil {
			u.JsonMsg(500, "", "密码加密失败")
		}
		request.Password = fmt.Sprintf("%s", bcryptByte)
	}
	now := time.Now().Format("2006-01-02 15:04:05")
	request.UpdatedAt = now
	if request.Id == 0 {
		request.CreatedAt = now
		accountExist := u.accountExist(request.Account)
		if accountExist {
			u.JsonMsg(500, "", "账号已经存在")
		}
		if request.Password == "" {
			u.JsonMsg(500, "", "请输入密码")
		}
		err = models.DB.Table("staff").
			Create(&request).Error
	} else {
		form := u.structToMap(request)
		delete(form, "created_at")
		if request.Password == "" {
			delete(form, "password")
		}
		err = models.DB.Table("staff").
			Where("id = ? and account = ?", request.Id, request.Account).
			Debug().
			UpdateColumns(&form).Error
	}
	if err == nil {
		u.JsonMsg(200, "", "保存成功")
	} else {
		u.JsonMsg(500, "", "保存失败")
	}
}

func (u *UserController) UserList() {
	var request userListProto
	var list []models.Staff
	var userCount int64
	err := u.ShouldBind(&request)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	if request.Limit > 100 {
		u.JsonMsg(500, "", "单页数据不能超过100条")
	}
	filter_keyword := fmt.Sprintf("%%%s%%", request.Keyword)
	limit := request.Limit
	skip := (request.Page - 1) * limit
	models.DB.Debug().Table("staff").
		Select("staff.id,staff.account,staff.mobile,staff.password,staff.username,staff.status,staff.avatar,staff.updated_at,staff.created_at,staff.role_id,staff.department_id,staff.shop_id,department.department_name,role.role_name,shop.shop_name").
		InnerJoins("INNER JOIN department ON staff.department_id = department.id").InnerJoins("INNER JOIN role ON staff.role_id = role.id").
		InnerJoins("INNER JOIN shop ON staff.shop_id = shop.id").
		Where("account like ? or mobile like ? or username like ?", filter_keyword, filter_keyword, filter_keyword).
		Count(&userCount)
	models.DB.Debug().Table("staff").
		Select("staff.id,staff.account,staff.mobile,staff.password,staff.username,staff.status,staff.avatar,staff.updated_at,staff.created_at,staff.role_id,staff.department_id,staff.shop_id,department.department_name,role.role_name,shop.shop_name").
		InnerJoins("INNER JOIN department ON staff.department_id = department.id").InnerJoins("INNER JOIN role ON staff.role_id = role.id").
		InnerJoins("INNER JOIN shop ON staff.shop_id = shop.id").
		Where("account like ? or mobile like ? or username like ?", filter_keyword, filter_keyword, filter_keyword).
		Offset(skip).
		Limit(limit).
		Order("id desc").
		Find(&list)
	u.JsonMsg(200, map[string]interface{}{
		"list":  list,
		"count": userCount,
	}, "success")
}

func (u *UserController) MyInfo() {
	var user models.Staff
	//models.DB.Table("Staff").
	//	Where("id = ?", GlobalUserInfo.Id).First(&user)
	models.DB.Table("staff").
		Select("staff.id,staff.account,staff.mobile,staff.password,staff.username,staff.status,staff.avatar,staff.updated_at,staff.created_at,staff.role_id,staff.department_id,staff.shop_id,department.department_name,role.role_name,shop.shop_name").
		InnerJoins("INNER JOIN department ON staff.department_id = department.id").InnerJoins("INNER JOIN role ON staff.role_id = role.id").
		InnerJoins("INNER JOIN shop ON staff.shop_id = shop.id").
		Where("staff.id = ?", GlobalUserInfo.Id).First(&user)
	u.JsonMsg(200, map[string]interface{}{
		"user": user,
	}, "success")
}

func (u *UserController) SaveMyinfo() {
	var request saveMyInfoProto
	err := u.ShouldBind(&request)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	if request.Password != "" {
		bcryptByte, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
		if err != nil {
			u.JsonMsg(500, "", "密码加密错误，请稍候重试")
		}
		password := fmt.Sprintf("%s", bcryptByte)
		request.Password = password
	}
	form := u.structToMap(request)
	form["updated_at"] = u.now()
	if form["password"] == "" {
		delete(form, "password")
	}
	err = models.DB.Debug().Table("staff").
		Where("id = ?", GlobalUserInfo.Id).
		UpdateColumns(form).Error
	if err == nil {
		u.JsonMsg(200, "", "保存成功")
	} else {
		u.JsonMsg(500, "", "保存失败")
	}
}
